'use strict';

const EventEmitter = require('events');
const async = require('async');

const PRIORITY = {
    HIGHT: 1,
    NORMAL: 3,
    LOW: 5
}
class Client extends EventEmitter {
    constructor(opts) {
        this._opts = opts;
        this._sendQueue = async.priorityQueue((task, callback) => {
            task(callback);
        });
    }
    connect() {
        function timeout() {

        }
        this._sock = new Socket(this._opts, () => {
            this.emit('ready');
        });
        this._sock.once('close', has_error => {
            this.emit('disconnect');
            if (has_error) {
                //try reconnect
                setTimeout(() => {
                    this.connect()
                }, 1000 * 3);//3秒后重新连接
            }
        })
        this._sock.on('data', data => {
            //TODO translate data to message
            this.receive(data);
        })
    }

    receive(message) {

    }
    send(message, priority) {
        this._sendQueue.push((done) => {
            //TODO translate message to data
            done(null);
        }, priority || PRIORITY.NORMAL, (error, result) => {

        })
    }
    reConnect() {
        this._sock && this._sock.destroy();
        this.connect();
    }
    disconnect() {
        this._sock.end();
    }
}